import React from "react";
import { sleep } from 'antd-mobile/es/utils/sleep'
import styles from '@/assets/css/order.module.css';
import type business from "@/types/business";
import type order from "@/types/order";

const Index = () => {
  const [business] = useState<business>(React.business);
  const [active, SetActive] = React.useState<string>('all');
  const [list, SetList] = React.useState<order[]>([]);
  const [hasMore, SetHasMore] = React.useState<boolean>(true);
  // 声明当前页
  const [page, setPage] = useState<number>(1);
  // 声明当前列表条数
  const [ListCount, setListCount] = useState<number>(0);

  // 选项卡切换事件
  const TabChange = async (key: string) => {
    SetActive(key);
    await sleep(1000);
    setPage(1);
    SetList([]);
    SetHasMore(true);
  }

  // 下拉刷新
  const OnRefresh = async () => {
    await sleep(1000);
    setPage(1);
    SetList([]);
    SetHasMore(true);
  };

  // 上拉加载
  const LoadMore = async () => {
    await sleep(1000);
    await fetchData();
  }

  // 获取订单数据
  const fetchData = async () => {
    // 组装参数
    const params = {
      busid: business.id,
      page,
      status: active
    };
    // 发起请求
    const result = await React.Http.post('/order/index', params);
    // 处理请求结果
    if (result.code === 1) {
      const count = result.data.count ?? 0;
      // 加载更多时合并数据
      SetList(v => {
        const newList = [...v, ...result.data.list];
        setListCount(newList.length);
        return newList;
      });
      // 停止条件
      if (count === ListCount) {
        SetHasMore(false);
        return;
      }
      // 继续加载
      SetHasMore(true);
      setPage(page => page + 1);
    } else {
      React.fail(result.msg);
      // 加载完成 -> 设置完成
      SetHasMore(false);
    }
  }

  // 按钮结构
  const ButtonList = (order: order, key: number) => {
    if (order.status == '3' && !order.rate) // 已入住 未评价
    {
      return (
        <React.UI.Button color='warning' size='small' onClick={() => React.navigate(`/order/info?orderid=${order.id}`)}>立即评价
        </React.UI.Button>
      )
    }
    else if (order.status == 1) // 已支付
    {
      return (
        <React.UI.Button color='danger' size='small' onClick={() => refund(order.id, key)}>申请退款</React.UI.Button>
      )
    }
  }

  // 申请退款
  const refund = (orderid: number, index: number) => {
    // 确认框
    React.UI.Dialog.confirm({
      title: '申请退款',
      content: '是否确认申请退款？',
      onConfirm: async () => {
        // 组装参数
        const params = {
          busid: business.id,
          orderid
        };
        // 发起请求
        const result = await React.Http.post('/order/refund', params);
        // 处理请求结果
        if (result.code === 1) {
          React.success(result.msg, () => {
            // 无刷新更新数组索引为index的status和status_text
            SetList((prevList) =>
              prevList.map((item, i) =>
                i === index ? { ...item, status: '-1', status_text: '申请退款' } : item
              )
            );
          });
        } else {
          React.fail(result.msg);
        }
      }
    })
  }

  return (
    <>
      {/* 选项卡切换 */}
      <React.UI.Tabs onChange={TabChange} activeKey={active} activeLineMode={'full'}>
        <React.UI.Tabs.Tab title="全部" key="all" />
        <React.UI.Tabs.Tab title="未支付" key="0" />
        <React.UI.Tabs.Tab title="已支付" key="1" />
        <React.UI.Tabs.Tab title="已入住" key="2" />
        <React.UI.Tabs.Tab title="已退房" key="3" />
        <React.UI.Tabs.Tab title="申请退款" key="-1" />
      </React.UI.Tabs>

      {/* 下拉刷新列表 */}
      <React.UI.PullToRefresh onRefresh={OnRefresh}>
        {/* 订单列表 */}
        <div className={styles.order_list}>
          {list && list.map((item: order, key: number) =>
            <div className={styles.item} key={key}>
              <div className={styles.item_top}>
                <p>{item.room.name}</p>
                <div className={styles.top_tag}>{item.status_text}</div>
              </div>

              <div className={styles.house}>
                <div className={styles.item_swipers}>
                  <img src={item.room.thumb_text} alt="" />
                </div>
                <div className={styles.item_times}>
                  <div>
                    <div>{item.starttime_text}</div>
                    <div>{item.startday_text}</div>
                  </div>
                  <div>
                    <div>共{item.order_day}晚</div>
                    <div className={styles.item_right}>
                      <img src="/assets/images/right1.png" alt="" />
                    </div>
                  </div>
                  <div>
                    <div>{item.endtime_text}</div>
                    <div>{item.endday_text}</div>
                  </div>
                  <div>
                    <div className={styles.item_pay}>订单总价</div>
                    <div className={styles.item_price}>￥{item.price}</div>
                  </div>
                </div>
              </div>

              <div className={styles.item_bar}>

                {ButtonList(item, key)}

                <React.UI.Button color='primary' size='small' onClick={() => React.navigate(`/order/info?orderid=${item.id}`)}>查看详情
                </React.UI.Button>
              </div>
            </div>
          )}
        </div>

        {/* 上拉加载 */}
        <React.UI.InfiniteScroll loadMore={LoadMore} hasMore={hasMore} threshold={0} />
      </React.UI.PullToRefresh>
    </>
  )
}

export default Index;